using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;

namespace MicroStar
{
    /// <summary>
    /// Default emitter to emit particles from a single point
    /// </summary>
    public class Emitter
    {
        // Additional Parameters
        private Color particleColor;
        private int particleLifespan;

        ///<summary>
        /// Constructor
        ///</summary>
        public Emitter()
        {
            Random = new Random();
            Force = new Randomize();
        }

        internal void Initialize(int size)
        {
            FreeParticles = new Queue<Particle>(size);
        }

        internal virtual void Emit(double elapsedMilliseconds, Vector2 position)
        {
            for (int i = 0; i < EmitAmount && FreeParticles.Count > 0; i++)
            {
                Particle newParticle = FreeParticles.Dequeue();
                InitializeParticle(ref newParticle, position, elapsedMilliseconds);
            }
        }

        internal void InitializeParticle(ref Particle particle, Vector2 position, double elapsedMilliseconds)
        {
            particle.IsAlive = true;
            particle.Alpha = 1;
            particle.Inception = (float)elapsedMilliseconds;
            particle.Position = position;
            particle.Color = particleColor;
            particle.Lifespan = particleLifespan;

            if (Force != null)
                Force.Initialize(ref particle);
        }

        internal int RandomEmissionAmount
        {
            get
            {
                int numParticles = Random.Next((int)(EmitAmount * 0.8), EmitAmount);
                if (numParticles < 1)
                    numParticles = 1;

                return numParticles;
            }
        }

        /// <summary>
        /// Gets or sets the amount of particles to emit each tick
        /// </summary>
        public int EmitAmount { get; set; }

        /// <summary>
        /// Gets or sets the force used for emitting particles
        /// </summary>
        public Force Force { get; set; }

        internal Queue<Particle> FreeParticles { get; private set; }
        internal Random Random { get; private set; }

        internal void SetAdditionalParameters(Color newColor, int newLifespan)
        {
            particleColor = newColor;
            particleLifespan = newLifespan;
        }
    }
}
